<template>
  <div class="login-container" >
    <div class="login-card">
        <h2>通用项目管理进度管理平台</h2>
        <el-form :model="formData" label-width="auto" style="max-width: 600px"
            :hide-required-asterisk="true">
            <el-form-item label="用户名：">
                <el-input 
                v-model="formData.username" 
                placeholder="请输入用户名"/>
            </el-form-item>
            <el-form-item label="密码：">
                <el-input 
                v-model="formData.password" 
                type="password"
                placeholder="请输入密码"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(formData)" style="margin: 0 auto;">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { login } from './api.js'

const router = useRouter()

// 表单数据
const formData = reactive({
  username: 'string',
  password: 'string'
})

//提交校验
const checkSubmitInfo=async (value)=> {
    const {username,password}=value
    if(!username){
        errorMsg("请输入用户名","warning")
        return false;
    }else if(!password){
        errorMsg("请输入密码","warning")
        return false;
    }else{
      return true;
    } 
}

const submitForm = async () => {
  const isValid = await checkSubmitInfo(formData);
  if (isValid) {
    const loading = ElLoading.service({
      background: "rgba(122, 122, 122, 0.8)",
    });
    try {
      const { code, data, message } = await login(formData);
      console.log('后端返回的数据:', { code, data, message }); // 打印后端返回的数据
      if (code === 200) {
        if (!data || !data.token || !data.username) {
          throw new Error('登录成功，但未返回完整的用户数据');
        }
        // 存储 token 和用户信息到 localStorage
        localStorage.setItem('token', data.token); // 存储 token
        localStorage.setItem('username', data.username); // 存储用户名
        localStorage.setItem('roleId', data.roleId); // 存储角色 ID
        localStorage.setItem('rolename', data.rolename); // 存储角色名称
        localStorage.setItem('userId', data.id); // 存储用户 ID
        localStorage.setItem('teamId', data.teamId); // 存储团队 ID（如果需要）

        loading.close();
        ElMessage({
          message: '登录成功',
          type: 'success',
        });
        router.push('/mainPage'); // 跳转到主页面
      } else {
        loading.close();
        ElMessage.error(message); // 显示后端返回的错误信息
      }
    } catch (error) {
      loading.close();
      ElMessage.error('登录失败，请稍后重试');
      console.error(error);
    }
  }
};

//错误信息
const errorMsg=async (msg,type)=>{
    ElMessage({
        message: msg,
        type: type,
    })
}


</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-image: url(../../assets/bgd.png);
  background-repeat: no-repeat;
  background-size: cover;
}

.login-card {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 1.5rem;
}

</style>